<template>
  <!-- 用户管理 -- 机构管理 -- 添加用户/编辑用户-->
  <div class="page-operate">
    <!-- 位置模块 -->
    <HeadTop></HeadTop>
    <div class="page-head">
      <span class="operate-text">{{title}}</span>
      <div class="operate-box">
        <button class="submit" @click="submitUserMsg">提交</button>
        <button @click="back()">关闭</button>
      </div>
    </div>
    <div class="content-area">
      <div class="form-edit add-user">
        <div class="page-form">
          <el-form :inline="true" status-icon class="my-form my-form-600" ref="myForm" :model="myForm"
                   label-width="120px" size="medium">
            <el-form-item label="用户名:" required>
              <el-input v-model="myForm.username"></el-input>
              <p class="password-warning" v-show="uid !== '0'">如果不需要修改密码,请不要填写密码与确定密码</p>
            </el-form-item>

            <el-form-item label="密码:" required>
              <el-input v-model="myForm.pass" type="password" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label="确认密码:" required>
              <el-input v-model="myForm.checkPass" type="password" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label="选择用户角色:" required>
              <el-select v-model="myForm.role" placeholder="--请选择用户组--">
                <el-option v-for="item in roleArr" :key="item.value" :label="item.label"
                           :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="选择机构:" required v-if="role >= 3">
              <el-autocomplete v-model="myForm.companyName"
                               :disabled="!hasRoleSelect"
                               :fetch-suggestions="searchCompanyName"
                               placeholder="请输入内容"
                               @select="handleSelect"
              ></el-autocomplete>
            </el-form-item>


            <el-form-item label="员工姓名:" required>
              <el-input v-model="myForm.realName "></el-input>
            </el-form-item>
            <el-form-item label="员工手机号码:" required>
              <el-input v-model="myForm.userPhone"></el-input>
            </el-form-item>

            <el-form-item label="权限选择:" required>
              <el-input placeholder="请选择权限" v-model="checkPower" readonly :disabled="!hasOrganSelect"
                        @focus="showAuthorityManage"></el-input>
            </el-form-item>
            <el-form-item label="邮箱:">
              <el-input v-model="myForm.email"></el-input>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>

    <dialogPowerSet ref="dialogPower" v-on:backstageNeedPower="setPower"></dialogPowerSet>
  </div>
</template>
<style lang="scss" type="text/scss">
  @import '../../../../style/entry/components/pageChildCommon';

  .select-authority-tree {
    width: 100%;
    height: 300px;
    overflow: auto;
  }

  .add-user form {
    display: flex;
    flex-direction: column;
  }
</style>
<script>
  import com from '../../../../js/common'
  import md5 from 'js-md5'
  import HeadTop from "../../../../components/head-top/head-top"

  import {queryOrgan, getUserDetail, getUserRbac, getLoginUserRbac, updateUserRbac} from '@/api/getData'

  import dialogPowerSet from "../../../../components/dialogPowerSet/dialogPowerSet"

  import {RoleArr} from '@/js/constant'


  /**
   * 1.操作用户权限在平台管理员之上才能选择机构,以下无法选择机构
   * 2.用户选择完角色以后,如果新建的是平台管理员,查询机构传type 99
   * 3.先选择角色,再选择机构,再选择权限,
   * 4.机构管理员及以下无需选择机构,页面一进来之时,就给departmentId 赋值
   *
   */

  export default {
    components: {
      HeadTop,
      dialogPowerSet
    },
    watch: {
      // 监听用户选择角色
      ['myForm.role']: function (newQuestion, oldQuestion) {
        if (this.myForm.role >= 0) {
          this.hasRoleSelect = true
        }
      },
      // 用户选择机构监听
      ['myForm.departmentId']: function () {
        if (this.role >= 3 && this.myForm.departmentId !== '') {
          this.hasOrganSelect = true
        } else if (this.role < 3) {
          this.hasOrganSelect = true
        } else {
          this.hasOrganSelect = false

        }
      }
    },
    data() {

      /* const checkEmail = function (rule, val, cal) {
         if (val === '') {
           cal()
         } else {
           const reg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
           if (!reg.test(val)) {
             cal(new Error('请输入正确邮箱'));
           } else {
             cal()
           }
         }
       }*/

      return {
        hasRoleSelect: false,  // 是否选择角色
        hasOrganSelect: false,  // 是否选择机构
        checkSearchOrgan: false, // 判断是否查询机构
        myForm: {
          pass: '',
          checkPass: '',
          username: '',
          realName: '',
          userPhone: '',
          user: '',
          role: '',
          email: '',
          companyName: '',
          regTime: '',
          departmentId: '',
          // 用户权限列表
          auths: [],
          // 是否选择用户角色等级是否大于平台管理员
          isSuper: true,
        },
        // 存储用户信息
        userMsg: {},
        title: '添加用户',
        uid: '0',
        roleArr: [],
        showDialogAuthorityTree: false,
        // 用户所能操作的权限
        userAuthorityTreeData: [],
        // 权限树名称
        defaultProps: {
          children: 'list',
          label: 'name'
        },
        // 用户已有权限
        userHasAuthority: [],
        // 权限code对应权限
        treeObj: {},
        checkPower: '',
        role: Number(com.getStore('role')),
      };
    },
    // 页面装载中
    created() {
      this.getUserMsg()
      this.checkUserRole()
    },
    methods: {
      // 根据登录用户 角色分配
      checkUserRole() {
        const arr = RoleArr
        const role = this.role
        this.roleArr = arr.filter((val) => {
          return val.value < role
        })
        //  4.机构管理员及以下无需选择机构,页面一进来之时,就给departmentId 赋值
        if (this.role < 3) {
          this.myForm.departmentId = com.getStore('departmentId')
          this.hasOrganSelect = true
        }
      },
      // 获取用户信息()
      getUserMsg() {
        const uid = this.$route.query.id
        const userId = this.$route.query.userId

        this.uid = uid
        this.userId = userId

        if (userId !== '0') {
          this.title = '编辑用户'
          this.checkPower = '已选择用户权限,点击修改'
          getUserDetail({
            userId: userId,
          }).then((res) => {
            // 存储用户信息
            this.userMsg = res.data.data
            // 存储用户展示信息
            this.myForm = res.data.data
            this.myForm.pass = ''
            this.myForm.checkPass = ''
          }).catch(err => this.$message.error(err.data.message))
        }
      },
      // 查询公司名称
      searchCompanyName(searchUrl, cb) {
        if (this.myForm.role === '') {
          cb([])
          this.$message.warning('请先选择用户角色')
          return
        }
        // 点击时置空公司
        this.myForm.departmentId = ''
        const param = {
          name: searchUrl,
        }
        // 新建平台管理员时,查询机构需要传type 99
        if (this.myForm.role == 3) {
          param.type = 99
        }
        queryOrgan(param).then(function (data) {
          let organList = data.data.data
          organList = organList.map((i) => {
            i.value = i.name
            return i
          })
          cb(organList)
        }).catch((err) => {
          this.$message.error(err.data.message)
        })
      },
      // 获取最后选择的机构
      handleSelect(item) {
        this.myForm.departmentId = item.id
      },
      // 显示权限树判断
      showAuthorityManage() {
        // 只有在用户角色高级的时候,才会选择机构,再选择权限可以选择机构时,才会这样
        if (this.role >= 3 && this.myForm.departmentId === '') {
          this.$message.warning('请先选择用户所属机构')
          return
        }
        // 此时获取用户权限
        if (this.uid !== '0') {
          let param = {}
          param.userId = this.userMsg.userId
          getUserRbac(param).then((res) => {
            const authorityArr = res.data.data
            this.$refs.dialogPower.getEleNeedPower(authorityArr)
          }).catch(err => this.$message.error(err.data.message))
        } else {
          let param = {}
          // 权限根据当前所选机构进行编辑
          param.departmentId = this.myForm.departmentId
          getLoginUserRbac(param).then((res) => {
            const authorityArr = res.data.data
            this.$refs.dialogPower.getEleNeedPower(authorityArr)
          }).catch(err => this.$message.error(err.data.message))
        }

      },
      // 编辑当前用户权限
      setPower(backNeedPower) {
        // 修改用户权限
        if (this.uid !== '0') {
          let params = {}
          // 通过遍历之后获取后台所需要的全部权限
          params.auths = backNeedPower
          params.user = {}
          params.user.userId = this.userMsg.userId
          updateUserRbac(params).then((res) => {
            com.mask()
            this.$message.success({
              message: '修改成功',
              duration: 1500,
              onClose: () => {
                com.unmask()
                this.$refs.dialogPower.hideDialog()
              }
            }).catch((err) => {
              this.$message.error(err.data.message)
              this.$refs.dialogPower.hideDialog()
            })
          })
        } else {
          this.myForm.auths = backNeedPower
          this.$refs.dialogPower.hideDialog()
          this.checkPower = '已选择用户权限,点击修改'
        }
      },
      // 1.点击提交时
      submitUserMsg() {
        if (!this.checkInput()) {
          return
        }
        if (this.uid !== '0') {
          // 编辑用户
          this.updateUser()
        } else {
          // 添加用户
          this.checkAddUser()
        }
      },
      // 2.校验必备字段输入
      checkInput() {
        // 用户名
        if (this.myForm.username === '') {
          this.$message.warning('请输入用户名')
          return false
        }
        // 密码
        if (this.myForm.pass !== this.myForm.checkPass) {
          this.$message.warning('请保持两次密码一致');
          return false
        }

        // 选择角色
        if (this.myForm.role === '') {
          this.$message.warning('请选择用户角色')
          return false
        }
        // 选择机构,除系统管理员以外都要选择机构
        if (this.myForm.role <= 3 && this.myForm.departmentId === '') {
          this.$message.warning('请选择机构')
          return false
        }
        // 员工姓名
        if (this.myForm.realName === '') {
          this.$message.warning('请输入员工姓名')
          return false
        }
        // 手机号码
        if (!com.checkMobile(this.myForm.userPhone)) {
          this.$message.warning('请输入正确格式手机号')
          return false
        }

        return true
      },
      // 3.1添加用户前进行校验
      checkAddUser() {
        if (this.myForm.pass !== this.myForm.checkPass || this.myForm.pass === '') {
          this.$message.warning('请正确输入密码')
          return false
        }
        // 添加提示(当用户未分配权限时)
        if (this.myForm.auths.length === 0) {
          this.$confirm('您还未给予用户权限分配,是否前往分配', {
            confirmButtonText: '是',
            cancelButtonText: '否',
            type: 'warning'
          }).then(() => {
            this.showAuthorityManage()
          }).catch(() => {
            this.addUser()
          })
        } else {
          this.addUser()
        }
      },
      // 3.1.1.添加用户
      addUser() {
        const url = `${com.basePath}/usercenter-web/user/add`
        let param = {}
        param.user = Object.assign({}, this.myForm)
        delete param.user.pass
        delete param.user.checkPass
        param.user.password = md5(this.myForm.pass)
        param.auths = this.myForm.auths
        com.axio.post(url, param).then((res) => {
          com.mask()
          this.$message.success({
            message: '添加成功',
            duration: 1500,
            onClose: () => {
              com.unmask()
              this.$router.push('/manage/systemMgr/userMgr')
            }
          })
        }).catch((err) => {
          this.$message.error(err.data.message)
        })
      },
      // 3.2更新用户信息
      updateUser() {
        const url = `${com.basePath}/usercenter-web/user/update`
        let param = {}
        // 深拷贝第一层数据
        param = Object.assign({}, this.myForm)
        delete param.pass
        delete param.checkPass
        delete param.auths
        if (this.myForm.pass === '') {
        } else {
          if (this.myForm.pass !== this.myForm.checkPass) {
            this.$message.warning('密码应与确定密码相同')
          } else {
            param.password = md5(this.myForm.pass)
          }
        }
        com.axio.post(url, param).then((res) => {
          com.mask()
          this.$message.success({
            message: '修改成功',
            duration: 1500,
            onClose: () => {
              com.unmask()
              this.$router.push('/manage/systemMgr/userMgr')
            }
          })
        }).catch((err) => {
          this.$message.error(err.data.message)
        })
      },
      // 返回上一级
      back() {
        this.$router.go(-1)
      },
    }
  }
</script>
